'use strict';

/**
 * 申请加入分会成员的审批通知（申请结果通知）
 * 申请人   {{thing2.DATA}}
 * 联系电话 {{phone_number9.DATA}}
 * 申请机构 {{thing1.DATA}}
 * 申请类型 {{thing4.DATA}}
 * 申请时间 {{time14.DATA}}
 */
const MSG_KEY_AUDIT_NOTICE = "JvRynPzFi3MpFD2g5D6K7jtCmddUa9i5UyafL6nopxs";

/**
 * 分会成员审批页面
 */
const PAGE_URL_AUDIT = "pages/bni/bniMemberAudit";

/** 小程序的AppID */
const MP_APP_ID = "wx6e0575f65cf58e81";

/** 小程序的Secret */
const MP_APP_SECRET = "83efe2e372b78bbb7578556257f55baa";

// 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版
// const JUMP_TYPE = "developer";  // 开发版
const JUMP_TYPE = "trial";  // 体验版
// const JUMP_TYPE = "formal"; // 正式版

// 测试
const IS_FOR_TEST = true;
// const IS_FOR_TEST = false;

/** 内部平台管理员的信息 */
const SYSTEM_ADMINS = [
	{ openId: 'owT-q6_hJjasXVp3jfHqBcGVH3tY' }, 
	{ openId: 'owT-q6_XNA2U2NPS9ZcZmUcVFfkQ' },
];


module.exports = {
	_before: function () { // 通用预处理器
	 
	},
	
	async getMpAccessToken() {
		let url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + MP_APP_ID + "&secret=" + MP_APP_SECRET;
		// console.log(url);
		const res = await uniCloud.httpclient.request(url, {
			method: "GET",
			dataType: "json", // 此处指定为json表示将此请求的返回值解析为json
			timeout: 30000
		});
		// console.log("res",res);
		return res.data.access_token;
	},
	
	async sendMpMessage(openId, templateId, data, page, accessToken) {
		let url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
		let sendData = {
			"touser": openId, 
			"template_id": templateId,
			"data": data,
			"miniprogram_state": JUMP_TYPE,  // 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版
			"lang": "zh_CN"
		}
		if (page != null) {
			sendData['page'] = page
		}
		console.log('sendData:', JSON.stringify(sendData))
		const res = await uniCloud.httpclient.request(url, {
			method: "POST",
			dataType: "json", // 此处指定为json表示将此请求的返回值解析为json
			timeout: 30000, 
			data: JSON.stringify(sendData)
		});
		console.log("res",res);
		return res;
	},
	
	// 给分会管理员发送申请审核通知（传参：branchId, branchName, userName, phone, companyName）
	async sendMemberAuditMpMessageToAdmin(userInfo) {
		let accessToken = await this.getMpAccessToken();
		console.log('accessToken=', accessToken);
		
		// 根据branchId获取当前任期的分会管理员、查询分会管理员的openId
		// 给分会的管理员，逐一发送订阅消息通知
		var adminOpenIds = [];
		const db = uniCloud.database();
		let members = await db.collection("bni-branch-team").where({
			branchId: userInfo.branchId
		}).orderBy("count", "desc").limit(1).get();
		console.log('members:', members);
		if (members.data.length > 0) {
			let member = members.data[0];
			// 当前任期分会ID
			let teamId = member._id;
			
			// 查询分会的管理员
			let admins = await db.collection("bni-role-member").where({
				branchId: userInfo.branchId, 
				teamId: teamId,
				// ！！！这里应该要再根据角色code来过滤的，只能部分角色发消息通知
			}).get();
			console.log('admins:', admins);
			if (admins.data.length > 0) {
				var adminUserIds = [];
				for (var i = 0; i < admins.data.length; i++) {
					// 根据userId来获取openId
					let admin = admins.data[i];
					adminUserIds.push(admin.userId);
				}
				for (var i = 0; i < adminUserIds.length; i++) {
					let users = await db.collection("mp-user").where({
						_id: adminUserIds[i]
					}).get();
					console.log('users:', users);
					if (users.data.length > 0) {
						adminOpenIds.push({ openId: users.data[0].openId })
					}
				}
			}
		}
		
		// 申请加入分会成员的审批通知（申请结果通知）
		let now = new Date();
		// console.log('-----now:', now)
		let timeZoneOffset = now.getTimezoneOffset() / 60;
		if (timeZoneOffset == 0) {
			timeZoneOffset = 8;
			now.setHours(now.getHours() + timeZoneOffset);
		}
		// console.log('-----timeZoneOffset:', timeZoneOffset)
		// let nowTime = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
		let nowTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
		
		let sendData = {
			// 申请人   {{thing2.DATA}}
			"thing2": {
				"value": userInfo.userName ? userInfo.userName : '未填写'
			},
			// 联系电话 {{phone_number9.DATA}}
			"phone_number9": {
				"value": userInfo.phone ? userInfo.phone : '未填写'
			},
			// 申请机构 {{thing1.DATA}}
			"thing1": {
				"value": userInfo.companyName ? userInfo.companyName : '未填写'
			},
			// 申请类型 {{thing4.DATA}}
			"thing4": {
				"value": "申请加入" + userInfo.branchName
			},
			// 申请时间 {{time14.DATA}}
			"time14": {
				"value": nowTime
			}
		};
		// console.log('sendData:', sendData);
		
		if (IS_FOR_TEST) {
			// 只发内部管理员
			adminOpenIds = SYSTEM_ADMINS;
		}
		console.log('adminOpenIds:', adminOpenIds);
		
		for (var i = 0; i < adminOpenIds.length; i++) {
			let result = await this.sendMpMessage(
				adminOpenIds[i].openId, 
				MSG_KEY_AUDIT_NOTICE, 
				sendData, 
				PAGE_URL_AUDIT + '?branchId=' + userInfo.branchId,
				accessToken
			);
			console.log('result:', result);
		}
	},
	
	async main(event, context) {
		//event为客户端上传的参数
		console.log('event : ', event);
		
		// 给用户发送申请加入分会成员通知
		await this.sendMemberAuditMpMessageToAdmin(event);
		
		///////
		// // 测试
		// let userInfo = {
		// 	branchId: "a72823ff657b1513034f76103fc082fe", 
		// 	branchName: "广诚分会", 
		// 	userName: "郑国里", 
		// 	phone: "18922782615", 
		// 	companyName: "广州云星互动网络科技有限公司", 
		// }
		// await this.sendMemberAuditMpMessageToAdmin(userInfo);
		///////
		
		//返回数据给客户端
		return event;
	}
}